using System;
using Quiki.ExpressionParsers;
using Quiki.Templates;

namespace Quiki.DocumentPostprocessors
{
    public class TocGenerator : IDocumentPostprocessor
    {
        public void PostProcessDocument(WikiDocument document)
        {
            if (AlreadyHasToc(document))
                return;

            if (CountHeadings(document) < 3)
                return;

            InsertTocTemplateElement(document);
        }

        private static bool AlreadyHasToc(WikiDocument document)
        {
            return null != document.RootElement.FindElement (
                               x => x.ElementType == WikiTextElementType.Template
                                    && ((WikiTemplateElement)x).TemplateName == TableOfContentsTemplate.TemplateId);
        }

        private static int CountHeadings(WikiDocument document)
        {
            return document.RootElement.CountElements(x => x.ElementType == WikiTextElementType.Heading && x.Level > 1);
        }

        private static void InsertTocTemplateElement(WikiDocument document)
        {
            WikiTemplateElement templateElement = new WikiTemplateElement(
                TableOfContentsTemplate.TemplateId,
                new string[0]);
            document.RootElement.ChildElements.Insert(0, templateElement);
        }
    }
}